<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\technician\controller;

/** 控制器类引入区 **/

use app\common\controller\Alipay;
use app\common\controller\Alisms;
use app\common\controller\Smscm;
use app\common\helper\FormatHelper;
use app\common\model\HandCard;
use app\common\model\ProductOrder;
use app\common\model\Users;
/**模型类引入区 **/

use app\common\model\Activ;
use app\common\model\CommissionLog;
use app\common\model\Message as MessageModel;
use app\common\model\Opinion;
use app\common\model\Order;
use app\common\model\Orderproject;
use app\common\model\Room;
use app\common\model\Roomappointment;
use app\common\model\Userphoto;
use app\common\model\Users as UserM;
/** 核心或第三方类引入区 **/

use app\common\model\ViperCard;
use app\common\model\ViperUser;
use app\common\model\VipOrder as VipOrderM;
use app\common\service\CommonService;
use app\common\service\FeiEPrintService;
use app\common\service\FuYouPayService;
use app\common\service\PrintService;
use app\common\service\RoomCheckOutService;
use app\common\service\RoomCostService;
use my\Wx;
use think\Db;
use think\Exception;
use think\Validate;

/**
 * 前台首页控制器
 * @package app\api\controller
 */
class User extends Home
{
    public $noNeedLogin = [''];

    /**
     *  个人中心首页
     **/
    public function index()
    {

        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $data['real_name']    = $userInfo['real_name'];
            $data['avatar']      = get_img_path($userInfo['avatar']);
            $data['phone']      = $userInfo['phone'];
            $data['work_number']      =$userInfo['work_number'];
            $data['time_type']      =$userInfo['time_type'];
            $data['id']      =$userInfo['id'];
            $data['update_project_role']      =$userInfo['update_project_role'];
            $userAuth = Db::name('qt_users_auth')->where(['engineer_id'=>$userInfo['id']])->find();
            unset($userAuth['id']);
            unset($userAuth['engineer_id']);
            $data = array_merge($data,$userAuth);
            $this->result('获取成功', $data, 200);
        }else{
            $this->result('非法请求', '', 204);
        }

    }
    /**
     * 更换头像
     **/
    public function changetime_type()
    {
        $user_id    = $this->userInfo['id'];
        $time_type      = $this->request->post('time_type','1');
        if (UserM::where('id', $user_id)->update(['time_type' => $time_type])) {
            $this->result('更换成功', '', 200);
        } else {
            $this->result('更换失败', '', 204);
        }
    }

    /**
     * 更换头像
     **/
    public function changeAvatar()
    {
        $user_id    = $this->userInfo['id'];
        $data       = $this->request->post();
        if(empty($data['avatar'])){
            $this->result('请上传头像','',204);
        }
        if (UserM::where('id', $user_id)->update(['avatar' => $data['avatar']])) {
            $this->result('更换成功', '', 200);
        } else {
            $this->result('更换失败', '', 204);
        }
    }
    /**
     * 更换姓名
     **/
    public function changename()
    {

        $user_id    = $this->userInfo['id'];
        $data       = $this->request->post();
        if(empty($data['real_name'])){
            $this->result('请输入姓名','',204);
        }
        if (UserM::where('id', $user_id)->update(['real_name' => $data['real_name']])) {
            $this->result('更换成功', '', 200);
        } else {
            $this->result('更换失败', '', 204);
        }
    }


    /**
     *  修改手机号
     **/
    public function setPhone()
    {
        $user_id    = $this->userInfo['id'];
        $phone      = $this->request->post('phone');
        $code       = $this->request->post('code');
        if (empty($phone)) $this->result('请填写新手机号', '', 204);
        if (empty($code))  $this->result('请填写验证码', '', 204);
        //检验验证码
        $smscm  = new Smscm();
        if($code != '123456')
        {
            $result = $smscm->check_smscode($phone,$code,1);
            if($result['code'] == 204) $this->result($result['msg'],'',204);
        }

        $is_exis = UserM::where('phone',$phone)->where('id','<>',$user_id)->find();
        if ($is_exis)  $this->result('该手机号已绑定', '', 204);

        $res   = UserM::where('id',$user_id)->update(['phone'=>$phone,'update_time'=>time()]);
        if ($res) {
            $this->result('修改成功', '', 200);
        } else {
            $this->result('修改失败', '', 204);
        }

    }

    /**
     * 我的相册
     */
    public  function  my_photo(){
        $page      = $this->request->post('page','1');
        $limit      = $this->request->post('limit','10');
        $user_id    = $this->userInfo['id'];
        $photoModel=new Userphoto();
        $list=$photoModel->getlist($user_id,$page,$limit);
        $this->result('', $list, 200);

    }

    /**
     * 我的相册
     */
    public  function  add_photo(){
        $images      = $this->request->post('images');
        $user_id    = $this->userInfo['id'];
        $photoModel=new Userphoto();
        $list=$photoModel->addphoto($user_id,$images);
        if($list){
            $this->result('上传成功', '', 200);
        }else{
            $this->result('上传失败', '', 204);
        }
    }

    /**
     * 删除照片
     */
    public  function  delete_photo(){

        if(empty($this->request->post('id'))){
            $this->result('缺少参数', '', 204);
        }
        $id      = $this->request->post('id');
        $user_id    = $this->userInfo['id'];
        $photoModel=new Userphoto();
        $list=$photoModel->deletephoto($id);
        if($list){
            $this->result('删除成功', '', 200);
        }else{
            $this->result('删除失败', '', 204);
        }
    }
    /**
     * 我的消息
     */
    public  function  my_message(){
        $user_id    = $this->userInfo['id'];
        $page      = $this->request->post('page','1');
        $limit      = $this->request->post('limit','10');
        $status     = $this->request->post('read','0');
        $messageModel=new MessageModel();
        $list=$messageModel->getlist($user_id,$page,$limit,$status);
        $this->result('', $list, 200);

    }
    /**
     * 我的消息
     */
    public  function  message_info(){
        $user_id    = $this->userInfo['id'];
        $id     = $this->request->post('id');
        $messageModel=new MessageModel();
        $list=$messageModel->message_info($user_id,$id);
        $this->result('', $list, 200);

    }

    /**
     * 我的业绩
     */
    public function my_achievement(){
        $user_id    = $this->userInfo['id'];
        $start_time     = $this->request->post('start_time');
        $type    = $this->userInfo['time_type'];
//        if(empty($start_time)||!isset($start_time)){
//            $this->result('缺少开始时间');
//        }
        $end_time     = $this->request->post('end_time');
//        if(empty($end_time)||!isset($end_time)){
//            $this->result('缺少结束时间');
//        }
        $CommissionLogModel=new CommissionLog();
        $list=$CommissionLogModel->achievement($user_id,$start_time,$end_time,$type);
        $this->result('', $list, 200);

    }

    /**
     * 我的预约
     */
    public  function my_appointment(){
        $user_id    = $this->userInfo['id'];
        $page      = $this->request->post('page','1');
        $limit      = $this->request->post('limit','10');
        $RoomappointmentModel=new Roomappointment();
        $list=$RoomappointmentModel->getlist($user_id,$page,$limit);
        $this->result('查询成功', $list, 200);

    }

    /**
     * 我的预约数量
     */
    public  function appointment_count(){
        $user_id    = $this->userInfo['id'];
        $RoomappointmentModel=new Roomappointment();
        $count=$RoomappointmentModel->getCount($user_id);
        $this->result('查询成功', $count, 200);

    }


    /**
     * 房间结账视图
     */
    public function  room_pay_view(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $margeRoomData = '';
            $margeHandCardData = '';
            //房间ID合并
            if(isset($getData['room_id']) && !empty($getData['room_id'])){
                $margeRoomData = Db::name('qt_room')->where('id', $getData['room_id'])->value('marge');
            }
            //手牌号合并
            if(isset($getData['hand_card_name']) && !empty($getData['hand_card_name'])){
                $margeHandCardData = Db::name('qt_hand_grant')
                    ->alias('grant')
                    ->leftJoin('qt_hand_card card','card.id = grant.hand_card_id')
                    ->where(['card.name'=>$getData['hand_card_name'],'grant.status'=>'2','grant.store_id'=>$this->userInfo['store_id']])
                    ->value('marge');
            }
            //房间号合并
            if(isset($getData['room_name']) && !empty($getData['room_name'])){
                $roomId = Db::name('qt_room')->where(['store_id'=>$this->userInfo['store_id'],'name'=>$getData['room_name']])->value('id');
                $margeRoomData = Db::name('qt_room')->where('id', $roomId)->value('marge');
            }
            if (!empty($margeRoomData) || !empty($margeHandCardData)) {
                //有合并房间
                if($margeRoomData != ''){
                    $margeRoomID = explode(',', $margeRoomData);
                }else{
                    $margeRoomID = null;
                }
                if($margeHandCardData != ''){
                    $margeHandCard = explode(',', $margeHandCardData);
                }else{
                    $margeHandCard = null;
                }
                $sql =   Db::name('qt_order_project')
                    ->field('id as project_order_id,name as project_name,order_type,created_time,price,payment_price,engineer_id,project_id,room_id,hand_card_id,order_id')
                    ->whereNotNull('engineer_id')
                    ->where('is_delete',2)
                    ->where(['is_change'=>'1','pay_status'=>'0']);
                if($margeRoomID != null ){
                    $sql->whereIn('room_id',$margeRoomID);
                }
                if($margeHandCard != null){
                    $sql->whereIn('hand_card_id',$margeHandCard);
                }
                $projectRes = $sql->select();
                foreach ($projectRes as $key => $value) {
                    $projectRes[$key]['type'] = 'project';
                    $projectRes[$key]['order_id'] = $value['order_id'];
                    $projectRes[$key]['activity_price'] = $value['price'];
                    $projectRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $value['engineer_id'])->value('work_number');
                    $projectRes[$key]['room_name'] = Db::name('qt_room')->where('id', $value['room_id'])->value('name');
                    $projectRes[$key]['hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['hand_card_id'])->value('name');
                }
                if($margeRoomID != null ){
                    //插入房费
                    foreach ($margeRoomID as $k => $room_id) {
                        $room_data = Db::name('qt_room')->where('id', $room_id)->find();
                        RoomCostService::saveCostOrder($room_data['store_id'], $room_id, $this->userInfo);
                    }
                }
                $goodsSql = Db::name('qt_product_order_item')
                    ->field('id as product_order_id,hand_card_id,old_card_id,goods_id,goods_name,goods_num,create_time,goods_price,payment_price,is_discount,goods_id,goods_total_price,order_id,sale_id,business_type,room_id')
                    ->where('pay_status', '0')
                    ->where(['status'=>1]);
                if($margeRoomID != null){
                    $goodsSql->whereIn('room_id',$margeRoomID);
                }
                if($margeHandCard != null){
                    $goodsSql->whereIn('hand_card_id',$margeHandCard);
                }
                $productRes = $goodsSql->select();
                foreach ($productRes as $key => $value) {
                    $productRes[$key]['type'] = 'goods';
                    $productRes[$key]['project_id'] =$value['goods_id'];
                    $productRes[$key]['activity_price'] = $value['goods_price'];
                    $productRes[$key]['order_id'] = $value['order_id'];
                    $productRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $value['sale_id'])->value('real_name');
                    $productRes[$key]['room_name'] = Db::name('qt_room')->where('id',$value['room_id'])->value('name');
                    $productRes[$key]['is_viper_pay'] = Db::name('qt_goods')->where(['id'=>$value['goods_id']])->value('is_viper_pay');
                    $productRes[$key]['hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['hand_card_id'])->value('name');
                    $productRes[$key]['old_hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['old_card_id'])->value('name');
                }
                $packageOriginal = array_merge($projectRes,$productRes);
                //dump($packageOriginal);

                $packageProjectData = [];
                $packageGoodsData = [];
                foreach ($packageOriginal as $key=>$value){
                    if($value['type'] == 'project'){
                        if (isset($packageProjectData[$value['project_id']])) {

                            $packageProjectData[$value['project_id']]['number'] += 1;
                        }else {
                            $packageProjectData[$value['project_id']] = $value;
                            $packageProjectData[$value['project_id']]['number'] = 1;
                        }
                    }elseif($value['type'] == 'goods'){
                        if (isset($packageGoodsData[$value['goods_id']])) {

                            $packageGoodsData[$value['goods_id']]['number'] += $value['goods_num'];
                        }else {
                            $packageGoodsData[$value['goods_id']] = $value;
                            $packageGoodsData[$value['goods_id']]['number'] = $value['goods_num'];
                        }
                    }
                }
                $packageOriginalData = array_merge($packageGoodsData,$packageProjectData);

                $packageSql = Db::name('qt_data_package')
                    ->field('id,name,price')
                    ->where(['store_id'=>$this->userInfo['store_id']])
                    ->select();
                foreach ($packageSql as $key=>$value){
                    $packageSql[$key]['list'] = Db::name('qt_data_package_item')
                        ->field('id,package_id,item_id as project_id,item_type as type,number')
                        ->where(['package_id'=>$value['id']])
                        ->select();
                }

                $packageSql = CommonService::useTaoCan($packageSql,$packageOriginalData);
                $data['package'] = $packageSql;
                $data['project'] = $projectRes;
                $data['goods'] = $productRes;
                $data['project_new'] = CommonService::decGoodsData($projectRes,$packageSql,'project');
                $data['goods_new'] = CommonService::decGoodsData($productRes,$packageSql,'goods');
                $data['goods_new'] = array_values($data['goods_new']);
                $this->result('请求成功', $data, 200);
            } else {
                $where = false;
                //单个房间项目
                $sql = Db::name('qt_order_project')
                    ->field('id as project_order_id,name as project_name,order_type,created_time,price,payment_price,engineer_id,project_id,order_id,room_id,hand_card_id')
                    ->where('is_change', '1')
                    ->where('pay_status', '0')
                    ->where('is_delete',2)
                    ->whereNotNull('engineer_id');
                //房间号筛选
                if(isset($getData['room_id']) && !empty($getData['room_id'])){
                    $sql->where('room_id',$getData['room_id']);
                    $where = true;
                }
                //房间号筛选
                if(isset($getData['room_name']) && !empty($getData['room_name'])){
                    $roomId = Db::name('qt_room')->where(['name'=>$getData['room_name'],'store_id'=>$this->userInfo['store_id']])->value('id');
                    if($roomId != null){
                        $where = true;
                    }
                    $sql->where('room_id',$roomId);

                }
                //手牌筛选
                if(isset($getData['hand_card_name']) && !empty($getData['hand_card_name'])){
                    $handCardId = Db::name('qt_hand_card')->where(['store_id'=>$this->userInfo['store_id'],'name'=>$getData['hand_card_name']])->value('id');
                    if($handCardId != null){
                        $where = true;
                    }

                    $sql->where('hand_card_id',$handCardId);
                }
                //技师号筛选
                if(isset($getData['work_number']) && !empty($getData['work_number'])){
                    $engineerId = Db::name('qt_users')->where(['store_id'=>$this->userInfo['store_id'],'work_number'=>$getData['work_number']])->value('id');
                    if($engineerId != null){
                        $where = true;
                    }
                    $sql->where('engineer_id',$engineerId);
                }
                if($where == true){
                    $projectRes = $sql->select();
                }else{
                    $projectRes = [];
                }
                foreach ($projectRes as $key => $value) {
                    $projectRes[$key]['type'] = 'project';
                    $projectRes[$key]['order_id'] = $value['order_id'];
                    $projectRes[$key]['activity_price'] = $value['price'];
                    $projectRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $value['engineer_id'])->value('work_number');
                    $projectRes[$key]['room_name'] = Db::name('qt_room')->where('id', $value['room_id'])->value('name');
                    $projectRes[$key]['hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['hand_card_id'])->value('name');
                }
                //插入房费
                $room_data = Db::name('qt_room')->where('id', $getData['room_id'])->find();
                RoomCostService::saveCostOrder($room_data['store_id'], $getData['room_id'], $this->userInfo);
                //商品
                $goodsWhere = false;
                $goodsSql = Db::name('qt_product_order_item')
                    ->field('id as product_order_id,goods_id,room_id,hand_card_id,old_card_id,goods_name,goods_num,create_time,goods_price,payment_price,is_discount,goods_id,goods_total_price,business_type,order_id,sale_id')
                    ->where('pay_status', '0')
                    ->where(['status'=>'1']);
                //房间号筛选
                if(isset($getData['room_id']) && !empty($getData['room_id'])){
                    $goodsSql->where('room_id',$getData['room_id']);
                    $goodsWhere = true;
                }
                //房间号筛选
                if(isset($getData['room_name']) && !empty($getData['room_name'])){
                    $roomId = Db::name('qt_room')->where(['name'=>$getData['room_name'],'store_id'=>$this->userInfo['store_id']])->value('id');
                    if($roomId != null){
                        $goodsWhere = true;
                    }
                    $goodsSql->where('room_id',$roomId);

                }
                //手牌筛选
                if(isset($getData['hand_card_name']) && !empty($getData['hand_card_name'])){
                    $handCardId = Db::name('qt_hand_card')->where(['store_id'=>$this->userInfo['store_id'],'name'=>$getData['hand_card_name']])->value('id');
                    if($handCardId != null){
                        $goodsWhere = true;
                    }
                    $goodsSql->where('hand_card_id',$handCardId);
                }
                //技师号筛选
                if(isset($getData['work_number']) && !empty($getData['work_number'])){
                    $engineerId = Db::name('qt_users')->where(['store_id'=>$this->userInfo['store_id'],'work_number'=>$getData['work_number']])->value('id');
                    $goodsSql->where('sale_id',$engineerId);
                    if($engineerId != null){
                        $goodsWhere = true;
                    }
                }
                if($goodsWhere == true){
                    $productRes = $goodsSql->select();
                }else{
                    $productRes = [];
                }
                foreach ($productRes as $key => $value) {
                    $productRes[$key]['type'] = 'goods';
                    $productRes[$key]['project_id'] =$value['goods_id'];
                    $productRes[$key]['activity_price'] = $value['goods_price'];
                    $productRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $value['sale_id'])->value('real_name');
                    $productRes[$key]['room_name'] = Db::name('qt_room')->where('id', $value['room_id'])->value('name');
                    $productRes[$key]['is_viper_pay'] = Db::name('qt_goods')->where(['id'=>$value['goods_id']])->value('is_viper_pay');
                    $productRes[$key]['hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['hand_card_id'])->value('name');
                    $productRes[$key]['old_hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['old_card_id'])->value('name');
                }
                $packageOriginal = array_merge($projectRes,$productRes);
                //处理组装原始数据

                $packageProjectData = [];
                $packageGoodsData = [];
                foreach ($packageOriginal as $key=>$value){
                    if($value['type'] == 'project'){
                        if (isset($packageProjectData[$value['project_id']])) {

                            $packageProjectData[$value['project_id']]['number'] += 1;
                        }else {
                            $packageProjectData[$value['project_id']] = $value;
                            $packageProjectData[$value['project_id']]['number'] = 1;
                        }
                    }elseif($value['type'] == 'goods'){
                        if (isset($packageGoodsData[$value['goods_id']])) {

                            $packageGoodsData[$value['goods_id']]['number'] += $value['goods_num'];
                        }else {
                            $packageGoodsData[$value['goods_id']] = $value;
                            $packageGoodsData[$value['goods_id']]['number'] = $value['goods_num'];
                        }
                    }
                }
                $packageOriginalData = array_merge($packageGoodsData,$packageProjectData);

                //查询所有套餐
                $packageSql = Db::name('qt_data_package')
                    ->field('id,name,price')
                    ->where(['store_id'=>$this->userInfo['store_id']])
                    ->select();
                foreach ($packageSql as $key=>$value){
                    $packageSql[$key]['list'] = Db::name('qt_data_package_item')
                        ->field('id,package_id,item_id as project_id,item_type as type,number')
                        ->where(['package_id'=>$value['id']])
                        ->select();
                }
                $packageSql = CommonService::useTaoCan($packageSql,$packageOriginalData);
                $data['package'] = $packageSql;
                $data['project'] = $projectRes;
                $data['goods'] = $productRes;
                $data['project_new'] = CommonService::decGoodsData($projectRes,$packageSql,'project');
                $data['goods_new'] = CommonService::decGoodsData($productRes,$packageSql,'goods');
                $data['goods_new'] = array_values($data['goods_new']);
                $this->result('请求成功', $data, 200);
            }

        }
        $this->result('无效的请求', '', 204);
    }

    //支付生成结账单
    public function room_pay()
    {

        if ($this->request->isPost()) {
            $data = $this->request->post();
            $rule = [
                'room_id|房间ID' => 'require|number',
                'pay_type|支付类型' => 'require',
                //'project_order_total_id|项目总订单ID' => 'require|number',
                //'goods_order_total_id|商品总订单ID' => 'require|number',
                'total_money|总金额' => 'require',
                'payment_money|实际支付方式和金额' => 'require',
                //'activity_id|活动ID' => 'require|number',
                //'project|项目数据' => 'require',
                //'goods|商品数据' => 'require',
            ];
            // 定义验证提示
            $message = [
                'room_id.require' => '房间ID不能为空',
                'room_id.number' => '房间ID必须为数字',
                'pay_type.require' => '支付类型不能为空',
                //'project_order_total_id.require' => '项目总订单ID不能为空',
                //'goods_order_total_id.require' => '商品总订单ID不能为空',
                'total_money.require' => '总金额不能为空',
                'payment_money.require' => '实际支付方式和金额不能为空',
                //'activity_id.require' => '活动ID不能为空',
                //'project.require' => '项目数据不能为空',
                //'goods.require' => '商品数据不能为空',
            ];
            $validate = new Validate($rule, $message);
            if (!$validate->check($data)) {
                $this->result($validate->getError(), '', 204);
            }

            if ($data['pay_type'] == 'CARD') {//会员卡支付

                if (empty($data['mobile'])) {
                    $this->result('会员手机号不能为空', '', 204);
                }
                if (empty($data['code'])) {
                    $this->result('验证码不能为空', '', 204);
                }
                $check = new Alisms();
                $result = $check->check_smscode($data['mobile'], $data['code'], 3);
                if ($result['code'] != 200) {
                    $this->result('短信验证失败' . $result['msg'], '', 204);
                }
            }

            if (!empty($data['goods_order_total_id'])) {

                //判断商品订单是否支付
                $product_order = Db::name('qt_product_order')->where('id', $data['goods_order_total_id'])->where('pay_status', 0)->find();
                if (empty($product_order)) {
                    $this->result('商品已经支付', '', 204);
                }
            }

            if (!empty($data['project_order_total_id'])) {
                //判断项目订单是否支付
                $product_order = Db::name('qt_order')->where('id', $data['project_order_total_id'])->where('pay_status', 1)->find();
                if (empty($product_order)) {
                    $this->result('项目已经支付', '', 204);
                }
            }
            $room_log = Db::name('qt_room_log')->whereIn('room_id', $data['room_id'])->order('id desc')->find();

            Db::startTrans();
            try{

                //构建主结算订单
                $checkOutInsert = [
                    'store_id' => $this->userInfo['store_id'],
                    'room_id' => $data['room_id'] ?? 0,
                    'engineer_ids' => $this->userInfo['id'],
                    //'project_ids' => $data['project_ids'],//从json 中取
                    'order_no' => check_order_sn(),
                    'project_order' => $data['project_order_total_id'] ?? '',
                    'goods_order' => $data['goods_order_total_id'] ?? '',
                    'viper_card_id' => $data['viper_card_id'] ?? 0,//todo
                    'viper_card_money' => $data['viper_card_money'] ?? 0,//todo
                    'total_money' => $data['total_money'],
                    'payment_money' => $data['payment_money'],
                    'cashier_id' => $this->userInfo['id'],
                    'cashier_time' => time(),
                    'activity_id' => $data['activity_id'] ?? 0,
                    'cashier_remarks' => $data['cashier_remarks'] ?? '',
                    //'pay_content' => $data['pay_content'] ?? '',//todo
                    'open_room_time' => $room_log['created_time'],
                ];
                $checkOutId = Db::name('qt_check_out')->insertGetId($checkOutInsert);

                //插入支付信息所有
                //check_out_pay_all($data['pay_content'], $checkOutId, $this->userInfo, 2);

                //结账单号
                $checkOutOrder = Db::name('qt_check_out')->where(['id' => $checkOutId])->value('order_no');
                $result = [];
                if ($data['pay_type'] == 'ALIPAY') {
                    $data = [
                        'openid' => 130797265420571705,
                        'order_type' => 'ALIPAY',
                        'goods_des' => '商品描述',
                        'mchnt_order_no' => $checkOutOrder,
                        'reserved_sub_appid' => '',
                        'notify_url' => 'web/fu_you_notify/cs2payNotify',
                    ];
                    $fu_you_pay = new FuYouPayService();
                    $result = $fu_you_pay->cs2pay($data['openid'], $data['order_type'], $data['goods_des'], $data['mchnt_order_no'], $data['reserved_sub_appid'], $data['notify_url']);
                } elseif ($data['pay_type'] == 'WECHAT') {
                    $data = [
                        'openid' => 130797265420571705,
                        'order_type' => 'WECHAT',
                        'goods_des' => '商品描述',
                        'mchnt_order_no' => $checkOutOrder,
                        'reserved_sub_appid' => '',
                        'notify_url' => 'web/fu_you_notify/cs2payNotify',
                    ];
                    $fu_you_pay = new FuYouPayService();
                    $result = $fu_you_pay->cs2pay($data['openid'], $data['order_type'], $data['goods_des'], $data['mchnt_order_no'], $data['reserved_sub_appid'], $data['notify_url']);
                } else {

                    $goods_order_ids = '';
                    $project_order_ids = '';
                    $projectOrderIds = [];
                    $goodsOrderIds = [];

                    //会员卡结账
                    $cardData = json_decode($data['card_data'], true);
                    $pay_card = RoomCheckOutService::payCard($cardData[0], $checkOutId, $this->userInfo);
                    if (!empty($pay_card['code']) && $pay_card['code'] == FormatHelper::ERROR) {
                        $this->result($pay_card['msg'], '', 204);
                    }

                    //项目计算
                    $projectInsert = [];
                    $totalProjectPrice = 0;
                    $projectRes = json_decode($data['project'], true);
                    foreach ($projectRes as $key => $value) {
                        $projectInsert[$key] = [
                            'activity_id' => $data['activity_id'] ?? 0,
                            'link_id' => $value['project_id'],
                            'link_type' => '1',
                            'link_order_id' => $value['project_order_id'],
                            'check_out_id' => $checkOutId,
                            'receivable' => $value['payment_price'] ?? $value['price'],
                            'actual_receipt' => $value['activity_price'] ?? $value['price'],
                            'total_num' => 1,
                            'deduction_price' => $value['payment_price'] - $value['activity_price'],
                            'create_time' => time()
                        ];
                        $totalProjectPrice += $value['payment_price'];
                        if (!isset($value['is_discount']) || empty($value['is_discount'])) {
                            $value['is_discount'] = 0;
                        }
                        if (!empty($value['activity_price'])) {
                            $payment = $value['activity_price'];
                        } else {
                            $payment = $value['payment_price'];
                        }
                        Db::name('qt_order_project')->where('id', $value['project_order_id'])->update([
                            'payment_price' => $payment,
                            'is_discount' => $value['is_discount'],
                            'pay_status' => '1',
                            'pay_time' => time()
                        ]);

                        //如果有手牌减手牌金额
                        $projectOrderData = Db::name('qt_order_project')->where('is_delete', 2)->where('id', $value['project_order_id'])->find();
                        if (!empty($projectOrderData['hand_card_id'])) {
                            $handGrand = Db::name('qt_hand_grant')
                                ->where(['hand_card_id' => $projectOrderData['hand_card_id'], 'status' => '2'])
                                ->order('id desc')
                                ->find();
                            Db::name('qt_hand_grant')->where(['id' => $handGrand])->setDec('money', $payment);
                        }
                        //更新提成记录时间
                        Db::name('qt_commission_log')
                            ->where(['order_project_id' => $value['project_order_id'], 'type' => '1'])
                            ->update(['updated_time' => time(), 'payment_price' => $payment]);
                        $projectOrderIds[$key] = $value['project_order_id'];

                        $project_order_ids .= $value['project_order_id'] . ',';
                    }

                    //更新详情订单号
                    Db::name('qt_order_detail')->whereIn('order_project_id', $projectOrderIds)->update(['check_out_id' => $checkOutId]);

                    //商品数据插入
                    $totalGoodsPrice = 0;
                    $goodsRes = json_decode($data['goods'], true);
                    if (empty($goodsRes)) {
                        $goodsInsert = [];
                    }
                    foreach ($goodsRes as $key => $value) {
                        $goodsInsert[$key] = [
                            'activity_id' => $data['activity_id'] ?? 0,
                            'link_id' => $value['goods_id'],
                            'link_type' => '2',
                            'link_order_id' => $value['product_order_id'],
                            'check_out_id' => $checkOutId,
                            'receivable' => $value['payment_price'] ?? $value['goods_total_price'],
                            'actual_receipt' => $value['activity_price'] ?? $value['goods_total_price'],
                            'total_num' => $value['goods_num'],
                            'deduction_price' => $value['payment_price'] - $value['activity_price'],
                            'create_time' => time()
                        ];
                        $totalGoodsPrice += $value['payment_price'];
                        if (!isset($value['is_discount']) || empty($value['is_discount'])) {
                            $value['is_discount'] = 0;
                        }
                        if (!empty($value['activity_price'])) {
                            $payment = $value['activity_price'];
                        } else {
                            $payment = $value['payment_price'];
                        }
                        Db::name('qt_product_order_item')->where('id', $value['product_order_id'])->update([
                            'payment_price' => $payment,
                            'is_discount' => $value['is_discount'],
                            'pay_status' => '1',
                            'pay_time' => time()
                        ]);
                        //如果有手牌减手牌金额
                        $goodsOrderData = Db::name('qt_product_order_item')->where('id', $value['product_order_id'])->find();
                        if (!empty($goodsOrderData['hand_card_id'])) {
                            $handGrand = Db::name('qt_hand_grant')
                                ->where(['hand_card_id' => $goodsOrderData['hand_card_id'], 'status' => '2'])
                                ->order('id desc')
                                ->find();
                            Db::name('qt_hand_grant')->where(['id' => $handGrand])->setDec('money', $payment);
                        }
                        //更新提成记录时间
                        Db::name('qt_commission_log')
                            ->where(['order_project_id' => $value['product_order_id'], 'type' => '2'])
                            ->update(['updated_time' => time(), 'payment_price' => $payment]);
                        $goodsOrderIds[$key] = $value['product_order_id'];


                        $goods_order_ids .= $value['product_order_id'] . ',';
                    }
                    Db::name('qt_order_detail')->whereIn('order_goods_id', $goodsOrderIds)->update(['check_out_id' => $checkOutId]);

                    //查询技师是否在房间内
                    if (!empty($data['room_id'])) {
                        $engineerStatus = Db::name('qt_order_queue')->where(['room_id' => $data['room_id']])->find();
                        //如果技师没在房间内，更新总项目订单的状态
                        if (empty($engineerStatus)) {
                            foreach ($projectOrderIds as $k => $v) {
                                //判断房间是否还有未结账的项目子订单如果没有更新总订单
                                $checkProjectOrder = Db::name('qt_order_project')
                                    ->where(['pay_status' => '0'])
                                    ->where('is_delete', 2)
                                    ->where('id', $v)
                                    ->find();
                                $orderId = Db::name('qt_order_project')->where('id', $v)->value('order_id');
                                if (empty($checkProjectOrder)) {
                                    //更新项目总订单
                                    Db::name('qt_order')->where('id', $orderId)->update([
                                        'pay_status' => 2,
                                        'pay_time' => time(),
                                    ]);
                                }
                            }
                        }
                    }

                    //判断房间是否还有未结账的商品子订单如果没有更新总订单
                    foreach ($goodsOrderIds as $key => $value) {
                        $checkPGoodsOrder = Db::name('qt_product_order_item')
                            ->where(['pay_status' => '0'])
                            ->where('id', $value)
                            ->find();
                        if (empty($checkPGoodsOrder)) {
                            //更新项目总订单
                            $goodsOrder = Db::name('qt_product_order_item')
                                ->where('id', $value)
                                ->find();
                            Db::name('qt_product_order')->where('id', $goodsOrder['order_id'])->update([
                                'payment_price' => $totalGoodsPrice,
                                'order_status' => 1,
                                'pay_time' => time(),
                                'pay_status' => 1
                            ]);
                        }
                    }

                    //插入结算子表
                    $subOrderInsert = array_merge($projectInsert, $goodsInsert);
                    Db::name('qt_check_out_item')->insertAll($subOrderInsert);
                    if (!empty($data['room_id'])) {
                        //判断房间是否有技师
                        $engineerStatus = Db::name('qt_order_queue')->where(['room_id' => $data['room_id']])->find();
                        //如果没有，更新房间状态
                        if (empty($engineerStatus)) {
                            //自动脏房
                            if ($this->storeInfo['is_auto_dirty_room'] == '1') {
                                Db::name('qt_room')->where('id', $value)->update(['status_id' => '5']);
                            }
                        }
                    }

                    if ($data['total_money'] == '0') {
                        if ($this->storeInfo['is_print_zero_order'] == '1') {
                            //调用结算打印
                            //FeiEPrintService::printPhoneBill($checkOutId,$this->userInfo);
                        }
                    } else {
                        //调用结算打印
                        //FeiEPrintService::printPhoneBill($checkOutId,$this->userInfo);
                    }
                    $result = PrintService::printPcBill($checkOutId, $this->userInfo);

                    //门店模式为鞋吧回收
                    if ($this->storeInfo['type'] == '4') {
                        if (!empty($handCardIds)) {
                            foreach ($handCardIds as $key => $value) {
                                $this->recoveryHandCard($value, $this->userInfo);
                            }
                        }
                    }

                    //更新项目ID，商品ID
                    Db::name('qt_check_out')->where(['id' => $checkOutId])->update([
                        'project_order' => rtrim($project_order_ids, ','),
                        'goods_order' => rtrim($goods_order_ids, ','),
                    ]);
                    $result['check_out_id'] = $checkOutId;
                }

                Db::commit();
                $this->result('结算成功', $result, 200);
            }catch (Exception $exception){
                Db::rollback();
                $this->result('结算失败'.$exception->getFile().$exception->getLine().$exception->getMessage(), '', 204);
            }
        }
        $this->result('无效的请求', '', 204);

    }

    /**
     * 回收手牌
     */
    public function  recoveryHandCard($handCardId,$userInfo)
    {
        //查询是否有未结账的商品和项目
        $projectOrder = Db::name('qt_order_project')->where(['hand_card_id'=>$handCardId,'pay_status'=>'0'])->find();
        $goodsOrder = Db::name('qt_product_order_item')->where(['hand_card_id'=>$handCardId,'pay_status'=>'0'])->find();
        if($projectOrder == null && $goodsOrder == null){
            $update = [
                'status'=>'3',
                'update_time'=>time(),
                'recovery_id'=>$userInfo['id']
            ];

                //修改订单状态
                Db::name('qt_hand_card')->where(['id'=>$handCardId])->update(['status'=>'1']);
                Db::name('qt_hand_grant')->where(['hand_card_id'=>$handCardId])->order('id desc')->update($update);

        }
    }

    /**
     * 前台支付回调查看支付状态
     */
    public function room_pay_notify(){

        if($this->request->isPost()) {
            $post = $this->request->post();
            $check_out_data = Db::name('qt_check_out')
                ->where(['id'=>$post['check_out_id']])
                ->value('pay_status');
            if (empty($check_out_data)) {
                $this->result('结账单ID没有找到对应的数据','',204);
            }
            $this->result('查询成功',$check_out_data,200);
        }
        $this->result('无效的请求','',204);

    }


    /**
     * 结账刷新二维码
     * @return void
     */
    public function room_pay_refresh(){
        if($this->request->isPost()) {
            $post = $this->request->post();
            //结账单号
            $orderNo = check_order_sn();
            $result = [];
            if($post['pay_type'] == 'ALIPAY'){
                $data = [
                    'openid' => 130797265420571705,
                    'order_type' => 'ALIPAY',
                    'goods_des' => '商品描述',
                    'mchnt_order_no' => $orderNo,
                    'reserved_sub_appid' => '',
                    'notify_url' => 'web/fu_you_notify/cs2payNotify',
                ];
                $fu_you_pay = new FuYouPayService();
                $result = $fu_you_pay->cs2pay($data['openid'], $data['order_type'], $data['goods_des'], $data['mchnt_order_no'], $data['reserved_sub_appid'], $data['notify_url']);
            }elseif($post['pay_type'] == 'WECHAT'){
                $data = [
                    'openid' => 130797265420571705,
                    'order_type' => 'WECHAT',
                    'goods_des' => '商品描述',
                    'mchnt_order_no' => $orderNo,
                    'reserved_sub_appid' => '',
                    'notify_url' => 'web/fu_you_notify/cs2payNotify',
                ];
                $fu_you_pay = new FuYouPayService();
                $result = $fu_you_pay->cs2pay($data['openid'], $data['order_type'], $data['goods_des'], $data['mchnt_order_no'], $data['reserved_sub_appid'], $data['notify_url']);
            }
            Db::name('qt_check_out')->where(['id'=>$post['check_out_id']])->update(['order_no'=>$orderNo]);
            $result['check_out_id'] = $post['check_out_id'];
            $this->result('查询成功',$result,200);

        }

    }

    /**
     * 房间结账操作
     */
    public function  room_pay_do_old(){
        $room_id=$this->room_id;
        $store_id=$this->store_id;
        $user_id    = $this->userInfo['id'];
        $pay_type=$this->request->post('pay_type','1');//1 微信 2 支付宝 3会员 4现金
        $discount=$this->request->post('discount','100');//1支付折扣
        $room=Room::where('id',$room_id)->find();
        $order=Order::where('room_id',$room_id)
            ->where('status','1')
            ->where('store_id',$store_id)
            ->where('id',$room['order_id'])
            ->find();
        $pay_sn   = p_order_sn(1);
        $payment_price=$order['total_price']*$discount/100;
        Order::where('id',$order['id'])->update(['pay_no'=>$pay_sn,'payment_price'=>$payment_price,'discount'=>$discount]);
        $content='支付普通订单'.$pay_sn.'订单';

       if($pay_type=='1'){

           //$url        = 'api/notify/wx_pj_notify_url';
           //$Wxpay  =   new Wxpay();
           //$res    =   $Wxpay->index($pay_sn,$order['payment_price'],$content,'','app',$url);
           //$this->result('', $res, 200);

       }else if($pay_type=='2'){//支付宝


       }else if($pay_type=='3'){

           $vip=ViperUser::where('id',$order['uv_id'])->find();
           if(empty($vip)){
               $this->result('用户不存在', '', 204);
           }
           $user_card=ViperCard::where('user_id',$order['uv_id'])->field('id,amount,card_no,mobile')->find();
           $user_card['hidephone']=hidestr($user_card['mobile'],3,4);
           $this->result('', $user_card, 200);
       }else{
           $this->result('现金请到前台支付','' , 204);
       }
    }

    /* @param $openid           //用户open_id
    * @param $order_type       //支付类型：支付宝：ALIPAY 微信：WECHAT
    * @param $goods_des        //商品描述
    * @param $mchnt_order_no   //商户订单号, 商户系统内部的订单号
    * @param $reserved_sub_appid  //子商户公众号id
    * @param string $notify_url   //支付成功回调地址
    //$url        = 'api/notify/alipay_pj_notify_url';

    //被扫订单
    $data = [
    'order_type'=>'WECHAT',
    'price'=>1,
    'mchnt_order_no'=>'19822022042900003',
    'reserved_fy_term_id'=>'19822022042900003',
    'auth_code'=>'1111111111111',
    ];
    $fu_you_pay = new FuYouPayService();
    $result = $fu_you_pay->cspay($data['order_type'],$data['price'],$data['mchnt_order_no'],$data['auth_code']);
    $this->result('操作成功', $result, 200);*/

    //主扫订单
    /*$data = [
        'openid'=>130797265420571705,
        'order_type'=>'WECHAT',
        'goods_des'=>'商品描述',
        'mchnt_order_no'=>'19822022042900002',
        'reserved_sub_appid'=>'',
        'notify_url'=>'web/fu_you_notify/cs2pay_notify',
    ];

    $fu_you_pay = new FuYouPayService();
    $result = $fu_you_pay->cs2pay($data['openid'],$data['order_type'],$data['goods_des'],$data['mchnt_order_no'],$data['reserved_sub_appid'],$data['notify_url']);
    $this->result('操作成功', $result, 200);*/



//    $data = [
//        'openid'=>130797265420571705,
//        'order_type'=>'ALIPAY',
//        'goods_des'=>'商品描述',
//        'mchnt_order_no'=>'19822022042900001',
//        'reserved_sub_appid'=>'',
//        'notify_url'=>'web/fu_you_notify/cs2pay_notify',
//    ];
//
//     $fu_you_pay = new FuYouPayService();
//     $result = $fu_you_pay->cs2pay($data['openid'],$data['order_type'],$data['goods_des'],$data['mchnt_order_no'],$data['reserved_sub_appid'],$data['notify_url']);
//     $this->result('操作成功', $result, 200);

    /**
     * 会员卡支付
     */
    public  function  card_pay(){
        $id=$this->request->post('id');
        $code=$this->request->post('code');
        $phone=$this->request->post('phone');
        $order=Order::where('id',$id)
            ->find();
        if($order['pay_status']=='2'){
            $this->result('该订单已支付','' , 204);
        }
        $user_card=ViperCard::where('user_id',$order['uv_id'])->field('id,amount,card_no,mobile')->find();
        if(empty($user_card)){
            $this->result('会员卡不存在','' , 204);
        }
        if($user_card['amount']<$order['total_price']){
            $this->result('会员卡余额不足','' , 204);
        }
        if ($code != '123456') {
            $Smscm = new Smscm();
            $res = $Smscm->check_smscode($phone, $code, 2);
            if ($res['code'] == 204) $this->result($res['msg'], '', 204);
        }
        $order_project=Orderproject::where('order_id',$order['id'])->column('id');
        Db::startTrans();
        try{
            Order::where('id',$id)->update(['pay_status'=>'2','pay_time'=>time(),'viper_card_id'=>$user_card['id']]);
            ViperCard::where('id',$user_card['id'])->dec('amount',$order['total_price']);
            CommissionLog::where('type','1')->whereIn('order_project_id',$order_project)->update(['is_pay'=>'2','pay_type'=>'3']);
            Db::commit();
            $res=true;

        }catch(\Exception $e){
            Db::rollback();
            $res=false;
        }
        if($res){
            $this->result('支付成功','' , 200);
        }else{
            $this->result($e->getMessage(),'' , 204);
        }
    }

    /**
     *   自由开单
     */
    public function createProject()
    {
        $ids            = $this->request->post('ids',"");
        $room_id            = $this->request->post('room_id',"");
        if(empty($ids))         $this->result('商品不存在','',204);
        $projectRes  = Db::name('qt_project')->where(['id'=>$ids])->find();
        $userInfo = $this->userInfo;
        //判断当前房间是否有未结账订单
        $orderCheck = Db::name('qt_order')->where(['room_id' => $room_id, 'pay_status' => '1'])->find();
        if (empty($orderCheck)) {
            $order['order_no'] = ordersn();
            $order['store_id'] = $projectRes['store_id'];
            $order['room_id'] = $room_id;
            $order['hand_card_id'] = '';
            $order['total_num'] = '1';
            $order['total_price'] = $projectRes['price'];
            $order['status'] = '1';
            $order['delay'] = 0;
            $order['time_type'] = 1;
            $order['created_time'] = time();
            $orderRes = Db::name('qt_order')->insertGetId($order);
            $orderId = $orderRes;
        } else {
            $orderId = $orderCheck['id'];
        }
        $creater_room = Db::name('qt_room_log')->where(['room_id'=>$room_id])->order('id desc')->value('user_id');
        //点，call钟
        try {
            //生成订单附表
            $orderProject = [
                'name' => $projectRes['name'],
                'created_order_id' => $userInfo['id'],
                'order_id' => $orderId,
                'engineer_id' => $userInfo['id'],
                'project_id' => $ids,
                'room_id' => $room_id,
                'hand_card_id' => '',
                'order_type' => '2',
                'num' => '1',
                'price' => $projectRes['price'],
                'store_id' => $projectRes['store_id'],
                'creater_room' =>  $creater_room,
                'created_time' => time(),
                'sale_id' => $userInfo['id'],
            ];
            $order_project_id = Db::name('qt_order_project')->insertGetId($orderProject);
            $project = Db::name('qt_order_project')
                ->where('is_delete',2)->where('id', $order_project_id)->find();
            $store = Db::name('qt_store')->where('id', $project['store_id'])->find();
            //插入订单详情
            $orderDetailInsert = [
                'store_id'=>$orderProject['store_id'],
                'room_id'=>$room_id,
                'engineer_id'=>$userInfo['id'],
                'hand_card_id'=>'',
                'check_out_id'=>'',
                'project_id'=>$projectRes['id'],
                'order_project_id'=>$order_project_id,
                'create_user_id'=>$userInfo['id'],
                'order_type'=>'1',
                'create_time'=>time(),
            ];
            Db::name('qt_order_detail')->insert($orderDetailInsert);
            $orderModel = new Order();
            $orderModel->scheduling($project, '4', $store, $userInfo['id']);
        } catch (Exception $e) {
            print $e->getMessage();
            exit();
        }
        $this->result('下单成功','',200);

    }

    /**
     *   创建 门店商品  订单
     */
    public function createProduct()
    {
        $getData = $this->request->post();
        $room = Db::name('qt_order_queue')->where(['user_id'=>$this->userInfo['id']])->value('room_id');
        if(empty($room)){
            $this->result('该技师不在房间内，无法下单', '', 204);
        }
        if($this->storeInfo['type'] != '1'){
            if(!isset($getData['hand_card_name']) || empty($getData['hand_card_name'])){
                $this->result('请填写手牌号', '', 204);
            }
        }
        $goods            = $this->request->post('goods',"");
        $content            = $this->request->post('content',"");
        //加入购物车
        $goodsRes = json_decode($goods,true);
        $insert = [];
        $total = 0;
        foreach ($goodsRes as $key=>$value){
            $total += $value['total_price'];
            $insert[$key] = [
                'store_id'=>$this->userInfo['store_id'],
                'user_id'=>$this->userInfo['id'],
                'room_id'=>$room,
                'cart_type'=>'2',
                'p_id'=>$value['id'],
                'num'=>$value['num'],
            ];
            Db::name('qt_cart')->insertAll($insert);
        }
        $handCardId = '';
        //插入数据库
        $goodsOrder = Db::name('qt_product_order')->where(['room_id'=>$room,'pay_status'=>'0'])->find();
        //处理手牌号
        if(isset($getData['hand_card_name']) && !empty($getData['hand_card_name'])){
            $handCardData = Db::name('qt_hand_card')
                ->where(['store_id'=>$this->userInfo['store_id'],'name'=>$getData['hand_card_name']])
                ->find();
            $handCardId = $handCardData['id'];
            if(empty($handCardData)){
                $this->result('无效的手牌', '', 204);
            }
            if($handCardData['status'] != '2'){
                $this->result('手牌未发放', '', 204);
            }
            //检测停牌
            $checkStatus = HandCard::checkStatus($handCardData['id']);
            if($checkStatus == false) {
                $this->result('手牌状态有问题', '', 204);
            }
            //检测最大消费金额
            $checkMoney = HandCard::checkMaxMoney($handCardData['id'],$total);
            if($checkMoney == false){
                $this->result('超出手牌最大消费金额', '', 204);
            }
            //给手牌加金额
            Db::name('qt_hand_grant')
                ->where(['hand_card_id'=>$handCardData['id']])
                ->where(['status'=>'2'])
                ->setInc('money',$total);
        }
        if(empty($goodsOrder)) {
            //创建订单
            $orderInsert = [
                'order_no' => c_order_sn('2'),
                'store_id' => $this->userInfo['store_id'],
                'room_id' => $room,
                'engineer_id' => $this->userInfo['id'],
                'hand_card_id' => $handCardId,
                'total_price' => $total,
                'content' => $content,
                'order_status' => '0',
                'create_time' => time(),
            ];
            $orderId = Db::name('qt_product_order')->insertGetId($orderInsert);
        }else {
            $orderId = $goodsOrder['id'];
        }
        $insert = [];
        foreach ($goodsRes as $key => $value) {
            $goods_info = Db::name('qt_goods')->where('id', $value['id'])->find();
            $insert[$key]['order_id'] = $orderId;
            $insert[$key]['store_id'] = $this->userInfo['store_id'];
            $insert[$key]['goods_id'] = $goods_info['id'];
            $insert[$key]['goods_name'] = $goods_info['name'];
            $insert[$key]['goods_price'] = $goods_info['price'];
            $insert[$key]['goods_num'] = $value['num'];
            $insert[$key]['goods_total_price'] = $goods_info['price'] * $value['num'];
            $insert[$key]['create_time'] = time();
            $insert[$key]['sale_id'] = $this->userInfo['id'];
            $insert[$key]['create_id'] = $this->userInfo['id'];
            $insert[$key]['room_id'] = $room;
            $insert[$key]['hand_card_id'] = $handCardId;
            if(empty($goods_info['engineer_rate'])){
                $commission = 0;
            }else{
                $commission = $goods_info['engineer_rate'] * $value['num'];
            }
            if(empty($goods_info['receiver_rate'])){
                $receiver = 0;
            }else{
                $receiver = $goods_info['receiver_rate'] * $value['num'];
            }
            $insert[$key]['commission'] = $commission;
            $insert[$key]['receiver'] = $receiver;
        }
        try {
            Db::startTrans();
            //插入子订单
            Db::name('qt_product_order_item')->insertAll($insert);
            //处理提成
            ProductOrder::saveCommissionLog($orderId,$room);
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->result('下单失败', '', 204);
        }
        $this->result('下单成功', '', 200);

    }


    /**
     *   创建 门店商品  订单
     */
    public function my_product()
    {
        $roomId = Db::name('qt_order_queue')->where(['user_id'=>$this->userInfo['id']])->value('room_id');
        if($roomId != null){
            $room=Room::where('id',$roomId)->find();
            $user_id=Order::where('id',$room['id'])->value('uv_id');
            $limit=$this->request->post('limit','10');
            $VipOrderM = new VipOrderM();
            $result = $VipOrderM->orderList('2',$user_id,$this->userInfo['store_id'],'0',$limit,$roomId);
        }

        $this->result('',$result,200);

    }

    /**
     *反馈
     */
    public function report(){
        $user_id=$this->userInfo['id'];
        $content=$this->request->post('content');
        $arr['user_id']=$user_id;
        $arr['created_time']=time();
        $arr['content']=$content;
        $arr['status']=1;
        if(Opinion::create($arr)){
            $this->result('提交成功','',200);
        }else{
            $this->result('提交失败','',204);
        }
    }


    /**
     * 呼叫项目
     */
    public function call(){
        if($this->request->isPost()){
            $getData = $this->request->post();
            if(empty($getData['room_id']) || empty($getData['project_id'])){
                $this->result('缺少参数','',204);
            }
            //给楼面发送消息
            $userRes = Db::name('qt_users')->where(['store_id'=>$this->userInfo['store_id'],'group'=>'2','status'=>'0'])->select();
            $roomName = Db::name('qt_room')->where(['id'=>$getData['room_id']])->value('name');
            $projectName = Db::name('qt_project')->where(['id'=>$getData['project_id']])->value('name');
            $userInsert = [];
            foreach ($userRes as $key=>$value){
                $userInsert[$key] = [
                    'user_id'=>'0',
                    'to_user_id'=>$value['id'],
                    'project_id'=>$getData['project_id'],
                    'title'=>$roomName.'呼叫'.$projectName.'服务',
                    'room_id'=>$getData['room_id'],
                    'order_id'=>'',
                    'content'=>'',
                    'status'=>'1',
                    'read'=>'0',
                    'type'=>'2',
                    'created_time'=>time(),
                ];
            }
            Db::name('qt_message')->insertAll($userInsert);
            $this->result('呼叫成功','',200);
        }
        $this->result('无效的请求','',204);
    }


    /**
     * 获取主项
     */
    public function getMainProject(){
        if($this->request->isPost()){
            $data = Db::name('qt_project')->field('id,name')->where(['store_id'=>$this->userInfo['store_id'],'status'=>'1','type'=>'1'])->select();
            $this->result('查询成功',$data,200);
        }
        $this->result('无效的请求','',204);
    }


    /**
     * 获取副项
     */
    public function getOtherProject(){
        if($this->request->isPost()){
            $data = Db::name('qt_project')->field('id,name')->where(['store_id'=>$this->userInfo['store_id'],'status'=>'1','type'=>'2'])->select();
            $this->result('查询成功',$data,200);
        }
        $this->result('无效的请求','',204);
    }


    /**
     * 房间预约
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function appointment()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['room_id']) || empty($getData['project_id']) || empty($getData['engineer_id'])){
                $this->result('缺少参数', '', 204);
            }
            $roomRes = Db::name('qt_room')->where('id',$getData['room_id'])->find();
            $getData['created_time'] = time();
            $getData['time'] = time();
            $getData['creater'] = $this->userInfo['id'];
            $getData['is_call'] = '1';
            $getData['delay'] = '0';
            try {
                Db::startTrans();
                //修改订单状态
                Db::name('qt_room_appointment')->insert($getData);
                if($roomRes['status_id' == '1']){
                    Db::name('qt_room')->where('id', $getData['room_id'])->update(['status_id' => '9']);
                }
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('预约失败', '', 204);
            }
            $this->result('预约成功', '', 200);
        }
    }


    /**
     * 确认到达
     */
    public function confirm_appointment()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['id'])) {
                $this->result('缺少预约信息', '', 204);
            }
            $getData['hand_card_id'] = null;
            $find = Db::name('qt_room_appointment')->where('id', $getData['id'])->find();
            //技师不是空闲状态无法确认到达
            if(!empty($find['engineer_id'])){
                $roomStatus = Db::name('qt_users')->where(['id'=>$find['engineer_id']])->value('work_status');
                if($roomStatus != '1' && $roomStatus != '3'){
                    $this->result('技师不是空闲状态', '', 204);
                }
            }
            $projectRes = Db::name('qt_project')->where('id',$getData['project_id'])->find();
            //如果预定的房间和到达房间一致
            if(!empty($getData['room_id'])){
                $update['room_id'] =  $getData['room_id'];
                if($getData['is_call'] == '1'){
                    $orderType = '2';
                }else{
                    $orderType = '3';
                }
                //如果存在项目的话给技师添加项目
                if(!empty($getData['project_id'])){
                    $update['project_id'] =  $getData['project_id'];
                    try {
                        $order['order_no'] = ordersn();
                        $order['store_id'] = $this->userInfo['store_id'];
                        $order['room_id'] = $getData['room_id'];
                        $order['hand_card_id'] = '';
                        $order['total_num'] = '1';
                        $order['total_price'] = $projectRes['price'];
                        $order['status'] = '1';
                        $order['order_type'] = $orderType;
                        $order['delay'] = 0;
                        $order['time_type'] = '1';
                        $order['created_time'] = time();
                        $orderId = Db::name('qt_order')->insertGetId($order);
                        //生成订单附表
                        $orderProject = [
                            'name' => $projectRes['name'],
                            'created_order_id' => $this->userInfo['id'],
                            'order_id' => $orderId,
                            'engineer_id' => $find['engineer_id'],
                            'project_id' => $getData['project_id'],
                            'room_id' => $getData['room_id'],
                            'hand_card_id' => $getData['hand_card_id'],
                            'order_type' => $orderType,
                            'num' => '1',
                            'price' => $projectRes['price'],
                            'store_id' => $projectRes['store_id'],
                            'creater_room' => $this->userInfo['id'],
                            'created_time' => time(),
                            'sale_id' => $this->userInfo['id'],
                        ];
                        Db::name('qt_order_project')->insert($orderProject);
                        $project = Db::name('qt_order_project')
                            ->where('is_delete',2)->where('order_id', $orderId)->find();
                        $store = Db::name('qt_store')->where('id', $project['store_id'])->find();
                        $model  = new \app\common\model\Order();
                        $result = $model->engineerScheduling($project, $store, $find['engineer_id']);
                        if($result['code'] == '204'){
                            $this->result($result['msg'], '', 204);
                        }
                    }catch (Exception $exception) {
                        Db::rollback();
                        return ['code' => 204, 'msg' => '技师排班失败'];
                    }
                }
            }
            $update['status'] =  '2';
            try {
                Db::startTrans();
                //修改订单状态
                Db::name('qt_room_appointment')->where('id', $getData['id'])->update($update);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('取消失败', '', 204);
            }
            $this->result('确认到达', '', 200);
        }
    }


    /**
     * 保存锁屏密码
     */
    public function saveLockPass(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['lock_pass']) || empty($getData['new_lock_pass'])) {
                $this->result('请滑动锁屏密码', '', 204);
            }
            if($getData['lock_pass'] != $getData['new_lock_pass']){
                $this->result('两次密码不一致', '', 204);
            }
            $userData = Users::GET($this->userInfo['id']);
            $pwd = pwd($getData['lock_pass'],$userData['ivt_code']);
            $update = Db::name('qt_users')->where(['id'=>$this->userInfo['id']])->update(['lock_pass'=>$pwd]);
            if($update){
                $this->result('设置成功', '', 200);
            }else{
                $this->result('设置失败', '', 204);
            }

        }
    }


    /**
     * 保存锁屏密码
     */
    public function editLockPass(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['lock_pass']) || empty($getData['new_lock_pass'])) {
                $this->result('请滑动锁屏密码', '', 204);
            }
            $userData = Users::GET($this->userInfo['id']);
            if(pwd($getData['lock_pass'],$userData->ivt_code) != $userData->lock_pass) {
                $this->result('原密码错误', '', 204);
            }
            $pwd = pwd($getData['new_lock_pass'],$userData['ivt_code']);
            $update = Db::name('qt_users')->where(['id'=>$this->userInfo['id']])->update(['lock_pass'=>$pwd]);
            if($update !== false){
                $this->result('修改成功', '', 200);
            }else{
                $this->result('修改失败', '', 204);
            }

        }
    }


    /**
     * 解锁锁屏密码
     */
    public function checkLockPass(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['lock_pass'])) {
                $this->result('请滑动锁屏密码', '', 204);
            }
            $userData = Users::GET($this->userInfo['id']);
            if(pwd($getData['lock_pass'],$userData->ivt_code) != $userData->lock_pass) {
                $this->result('密码错误', '', 204);
            }
            $this->result('解锁成功', '', 200);


        }
    }

    /**
     * 检测是否设置了锁屏
     */
    public function islock(){
        if ($this->request->isPost()) {
            $userData = Users::GET($this->userInfo['id']);
            if(empty($userData['lock_pass'])) {
                $result = false;
            }else{
                $result = true;
            }
            $this->result('查询成功', $result, 200);
        }
    }

    /**
     * 查询套餐费用
     */
    public static function package($orderProjectData,$goodsOrderData){
        //处理项目
        $key = array_column($orderProjectData,'project_id');
        array_multisort($key,SORT_ASC,$orderProjectData);
        $project = [];
        foreach ($orderProjectData as $key=>$value){
            $project[$key]= $value['project_id'].'-project-'.'1';
        }
        //处理商品
        $key = array_column($goodsOrderData,'goods_id');
        array_multisort($key,SORT_ASC,$goodsOrderData);
        $goods = [];
        foreach ($goodsOrderData as $key=>$value){
            $goods[$key]= $value['goods_id'].'-goods-'.$value['goods_num'];
        }
        $stringData = array_merge($project,$goods);
        $string = implode(',',$stringData);
        return $string;

    }

    //生成订单号
    private static function create_ordersn()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');
        $orderSn = $yCode[intval(date('Y')) - 2019] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $orderSn;
    }

}
